package dao.impl;

import com.itany.jdbc.jdbc.JDBCTemplate;
import com.itany.jdbc.jdbc.KeyHoder;
import dao.UserDao;
import mapper.UserMapper;
import pojo.User;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.util.List;

/**
 * @author 陈华旺
 * @version 1.0
 * @date 2023年10月25日 16:11
 * @Description 构建实现类
 */
public class UserDaoImpl implements UserDao {
    private JDBCTemplate jt = new JDBCTemplate();
    private UserMapper um = new UserMapper();

    @Override
    public List<User> selectUserList() {
        String sql = "select id,name,sex,password,username from t_user";
//        JDBCTemplate jt = new JDBCTemplate();
        List<User> list = jt.query(sql, um);
        return list.isEmpty() ? null : list;
    }

    @Override
    public User selectUserByUsername(String username) {
        String sql = "select id,name,sex,password,username from t_user where username = ? ";
        return jt.queryOne(sql,um,username);
    }

    @Override
    public User selectUserByUsernameAndPassword(String username, String password) {
        String sql = "select id,name,sex,password,username from t_user where username = ? and password = ?";
        return jt.queryOne(sql,um,username,password);
    }

    @Override
    public void insertUser(User u) {
        String sql = "insert into t_user (name,sex,password,username) values (?,?,?,?)";
        jt.update(sql,u.getName(),u.getSex(),u.getPassword(),u.getUsername());
    }

    @Override
    public int insertUserReturnPK(User u) {
        KeyHoder keys = new KeyHoder();
        String sql = "insert into t_user (name,sex,password,username) values (?,?,?,?)";
//        jt.insertReturnPK(new PreparedStatementCreator() {
//            @Override
//            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
//                PreparedStatement ps = null;
//                ps = conn.prepareStatement(sql,new String[]{ "id" });
//                ps.setString(1,u.getName());
//                ps.setInt(2,u.getSex());
//                ps.setString(3,u.getPassword());
//                ps.setString(4,u.getUsername());
//                return ps;
//            }
//        },keys);
        jt.insertReturnPK(conn -> {
            PreparedStatement ps = null;
            ps = conn.prepareStatement(sql,new String[]{ "id" });
            ps.setString(1,u.getName());
            ps.setInt(2,u.getSex());
            ps.setString(3,u.getPassword());
            ps.setString(4,u.getUsername());
            return ps;
        },keys);
        return ((BigDecimal)keys.getKey()).intValue();
    }

}
